from paste.script.command import Command

import paste
import os
from  urllib2 import urlopen
import urllib
import json

from cpswarehouse.config.environment import load_environment

from cpswarehouse.model import SchoolDimension
from cpswarehouse.model import meta

from sqlalchemy import and_

def geocode(address):
    address = urllib.quote_plus(address)

    url = "http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % address
    data = urlopen(url).read()

    return json.loads(data)


class CpsGeocode(Command):
    # Parser configuration
    summary = "Geocode the school addresses that have been scraped from the cps.edu website."
    usage = "<settings_ini>"
    group_name = "cpswarehouse"
    parser = Command.standard_parser(verbose=False)

    def command(self):
        #make sure the config file arg is set
        if(len(self.args) != 1):
            print self.parser.format_help()
            return
        
        #load the environment
        conf_filename = os.path.abspath(self.args[0])
        conf = paste.deploy.appconfig("config:%s" % conf_filename)
        load_environment(conf.global_conf, conf.local_conf)
        
        schools = meta.Session.query(SchoolDimension).filter(and_(SchoolDimension.address != None, SchoolDimension.latitude == None, SchoolDimension.longitude == None))
        for school in schools:
            print school.school

        # address = "3017 W Lyndale, Chicago IL 60647"
            geocoded = geocode(school.address)

            if(geocoded['status'] == 'OK'):
                latitude = geocoded["results"][0]["geometry"]["location"]["lat"]
                longitude = geocoded["results"][0]["geometry"]["location"]["lng"]

                school.latitude = latitude
                school.longitude = longitude

                print latitude
                print longitude
        
        meta.Session.commit()


